import Foundation

/// 执行 Shell 命令 （会等待执行完成）
/// - Parameters:
///   - command: 命令
///   - path: 路径 默认为 "/bind/bash"，即 shell 脚本
/// - Returns: 运行结果和命令执行标准输出
@discardableResult
func shell(path: String = "/bin/bash", commands: String...) -> (status: Int, results: String) {
    let task = Process()
    task.executableURL = URL(fileURLWithPath: path)
    var environment = ProcessInfo.processInfo.environment
    environment["PATH"] = "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    task.environment = environment
    task.arguments = commands
    let pipe = Pipe()
    task.standardOutput = pipe
    task.launch()
    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output = String(data: data, encoding: String.Encoding.utf8)!
    task.waitUntilExit()
    pipe.fileHandleForReading.closeFile()
    return (Int(task.terminationStatus), output)
}

let (status, results) = shell(path: "/opt/homebrew/bin/periphery", commands: "scan")
if status == 0 {
    let fileManager = FileManager.default
    let currentPath = fileManager.currentDirectoryPath
    var url = URL(filePath: currentPath)
    url.append(path: "result.txt")
    do {
        try results.write(to: url, atomically: true, encoding: .utf8)
        print("结果保存路径：", url)
    } catch {
        print("error = ", error)
    }
}

// print(status, results)
